The switch structure is used when one wants to check the equality of a variable or expression against a list of values (constants).
General syntax:
switch(expression):
{
case constant1:
break;
case constant2:
break;
default:
break;
}
Where expression can take the values: constant1, constant2 or other value in which case the default branch will be executed. The expression must be evaluated at an integer, enumerated value or character.
First practical example:
#include <iostream>
int main()
{
int value = 0;
std::cout << "Please enter your grade from the math test you took yesterday (between 1 (worst) and 5 (best)): " << std::endl;
std::cin >> value;
switch(value)
{
case 1:
std::cout << "Lame!" << std::endl;
break;
case 2:
std::cout << "Keep learning!" << std::endl;
break;
case 3:
std::cout << "You did good!" << std::endl;
break;
case 4:
std::cout << "Very good!" << std::endl;
break;
case 5:
std::cout << "In the zone!" << std::endl;
break;
default:
std::cout << "Please enter an integer between 1 and 5!" << std::endl;
break;
}
}
Second practical example:
#include <iostream>
int main()
{
char firstLetter = 'x';
std::cout << "Please enter the first letter of the alphabet (uppercase letter): " << std::endl;
std::cin >> firstLetter;
switch(firstLetter)
{
case 'A':
std::cout << "Correct!" << std::endl;
break;
case 'a':
std::cout << "It is the first letter, but it is not uppercase letter!" << std::endl;
break;
default:
std::cout << "Wrong value!" << std::endl;
break;
}
}
There can be any number of cases and the default case is optional, although it is a good practice to use the default statement to handle other situations. A good practice is to surround the code in a case with braces when the code from that case exceeds one line (like below):
...
case 'X':
{
std::cout << "Begin long code... " << std::endl;
if(a condition)
{
}
else if(another condition)
{
}
else
{
}
std::cout << "End long code... " << std::endl;
}
break;
case 'Y':
...
When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.
When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.
When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.
Practical example:
#include <iostream>
int main()
{
char firstLetter = 'x';
std::cout << "Please enter the first letter of the alphabet (uppercase letter): " << std::endl;
std::cin >> firstLetter;
switch(firstLetter)
{
case 'A':
std::cout << "Correct!" << std::endl;
case 'a':
std::cout << "It is the first letter, but it is not uppercase letter!" << std::endl;
default:
std::cout << "Wrong value!" << std::endl;
}
}
In the example above, all three cout statements are executed because no break is found.